﻿using DevExpress.XtraEditors;
using MDK.Common;
using MDK.Device;
using MDK.Device.Devices;
using MDK.Model.Models;
using MDK.Winform;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MDK.Device.Components;

namespace MDK.Winform.UserControl.Config
{
    public partial class Position : BaseForm
    {
        private MitsubishiPlc plc;
        private PlcDevice device;
        private FrontDevice front;
        private BackDevice back;
        private Back2Device back2;
        private Centrifuge leftcentrifuge;
        private Centrifuge rightcentrifuge;
        private XYZRange range;
        private bool isFront;
        private bool isBack2;
        private bool isCentrifugeConnect;
        public Position()
        {
            InitializeComponent();
        }


        public Position(bool _isFront, bool _isBack2 = false) : this()
        {
            isFront = _isFront;
            isBack2 = _isBack2;
            if (!isFront)
            {
                tableLayoutPanelBehind.Visible = false;
                this.Height -= tableLayoutPanelBehind.Height;
            }
        }

        private void Position_Load(object sender, EventArgs e)
        {
            //GetConfigRange();
            InitPLC();
        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            leftcentrifuge = new Centrifuge(App.systemSetting["LeftCentrifuge"], int.Parse(App.systemSetting["LeftCentrifugePort"]));
            rightcentrifuge = new Centrifuge(App.systemSetting["RightCentrifuge"], int.Parse(App.systemSetting["RightCentrifugePort"]));
            isCentrifugeConnect = true;
        }

        public void GetConfigRange()
        {
            string fp = Application.StartupPath + (isFront ? "\\front" : "\\back") + ".json";
            if (File.Exists(fp))
            {
                range = JsonConvert.DeserializeObject<XYZRange>(File.ReadAllText(fp));  // 尖括号<>中填入对象的类名 
                txtXMin.Value = range.XMinimumLimit;
                txtXMax.Value = range.XMaximumLimit;
                txtYMin.Value = range.YMinimumLimit;
                txtYMax.Value = range.YMaximumLimit;
                txtZMin.Value = range.ZMinimumLimit;
                txtZMax.Value = range.ZMaximumLimit;
            }
            else
            {
                range = new XYZRange
                {
                    XMaximumLimit = decimal.MaxValue,
                    XMinimumLimit = decimal.MinValue,
                    YMaximumLimit = decimal.MaxValue,
                    YMinimumLimit = decimal.MinValue,
                    ZMaximumLimit = decimal.MaxValue,
                    ZMinimumLimit = decimal.MinValue,
                };
            }
        }

        private void cbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbPositionId.Properties.Items.Clear();
            if (cbType.SelectedIndex != 0)
            {
                PropertyHelper jsonWhere = new PropertyHelper();
                jsonWhere.Addproperty(CompareType.Equal, "PositionType", cbType.SelectedIndex);
                string url = string.Format("Position/FindList?jsonWhere={0}&orderPropertyName", JsonConvert.SerializeObject(jsonWhere.propertyList));
                var positionList = WebAPIHelper.Get<List<T_Position>>(url);
                cbPositionId.Properties.Items.AddRange(positionList);
            }
        }

        public void InitPLC()
        {
            try
            {
                //                string plcAddress = isFront ? App.systemSetting["PLCAddress2"] : isBack2 ? App.systemSetting["PLCAddress4"] : App.systemSetting["PLCAddress3"];
                //                plc = new MitsubishiPlc(plcAddress);
                //                plc.Open();
                //
                //                device = new PlcDevice(plc);
                //                device.SwitchAutoMode();


                if (isFront)
                {
                    front = SystemModel.Instance.Front;

                }
                else if (isBack2)
                {
                    back2 = SystemModel.Instance.Back2;
                }
                else
                {
                    back = SystemModel.Instance.Back;
                }

                Thread th = new Thread(RefreshDeviceStatus);
                th.IsBackground = true;
                th.Start();

            }
            catch { FastMessageBox.Error("初始化PLC失败，请检查配置"); }
        }

        private void RefreshDeviceStatus()
        {
            while (true)
            {
                try
                {
                    Thread.Sleep(1000);
                    if (this.IsHandleCreated)
                    {
                        if (isFront)
                        {
                            //初查
                            Sensor1.Invoke(new MethodInvoker(() =>
                            {
                                if (front.FingerCheckSensor.IsActive())
                                    Sensor49.Set2();
                                else
                                    Sensor49.Set1();
                            }));
                            //复查
                            Sensor2.Invoke(new MethodInvoker(() =>
                            {
                                if (front.FingerRecheckSensor.IsActive())
                                    Sensor49.Set2();
                                else
                                    Sensor49.Set1();
                            }));

                            //传感器
                            Sensor53.Invoke(new MethodInvoker(() =>
                            {
                                if (front.Z.MaximumSensor.IsActive())
                                    Sensor53.Set2();
                                else
                                    Sensor53.Set1();
                            }));

                            //传感器
                            Sensor54.Invoke(new MethodInvoker(() =>
                            {
                                if (front.Z.MinimumSensor.IsActive())
                                    Sensor54.Set2();
                                else
                                    Sensor54.Set1();
                            }));
                            txtZCurcoord.Invoke(new MethodInvoker(() =>
                            {
                                txtZCurcoord.Text = front.Z.CurrentCoord.ToString();
                            }));

                        }

                        txtXCurcoord.Invoke(new MethodInvoker(() =>
                        {
                            txtXCurcoord.Text = GetComponentById<IAxle>("X").CurrentCoord.ToString();
                        }));

                        txtYCurcoord.Invoke(new MethodInvoker(() =>
                        {
                            txtYCurcoord.Text = GetComponentById<IAxle>("Y").CurrentCoord.ToString();
                        }));

                        txtSZCurcoord.Invoke(new MethodInvoker(() =>
                        {
                            txtSZCurcoord.Text = GetComponentById<IAxle>("SZ").CurrentCoord.ToString();
                        }));
                        //X Error
                        lb1.Invoke(new MethodInvoker(() =>
                        {
                            if (GetComponentById<IAxle>("X").ErrorCode == 0)
                            {
                                lb1.ForeColor = Color.Green;
                            }
                            else
                            {
                                lb1.ForeColor = Color.Red;
                            }
                            lb1.Text = GetComponentById<IAxle>("X").ErrorCode.ToString();
                        }));

                        //Y Error
                        lb2.Invoke(new MethodInvoker(() =>
                        {
                            if (GetComponentById<IAxle>("Y").ErrorCode == 0)
                            {
                                lb2.ForeColor = Color.Green;
                            }
                            else
                            {
                                lb2.ForeColor = Color.Red;
                            }
                            lb2.Text = GetComponentById<IAxle>("Y").ErrorCode.ToString();
                        }));
                        //Z Error
                        lb3.Invoke(new MethodInvoker(() =>
                        {
                            if (isFront)
                            {
                                if (front.Z.ErrorCode == 0)
                                {
                                    lb3.ForeColor = Color.Green;
                                }
                                else
                                {
                                    lb3.ForeColor = Color.Red;
                                }
                                lb3.Text = front.Z.ErrorCode.ToString();
                            }

                        }));


                        //传感器
                        Sensor49.Invoke(new MethodInvoker(() =>
                        {
                            if (GetComponentById<IAxle>("X").MaximumSensor.IsActive())
                                Sensor49.Set2();
                            else
                                Sensor49.Set1();
                        }));

                        //传感器
                        Sensor50.Invoke(new MethodInvoker(() =>
                        {
                            if (GetComponentById<IAxle>("X").MinimumSensor.IsActive())
                                Sensor50.Set2();
                            else
                                Sensor50.Set1();
                        }));
                        //传感器
                        Sensor51.Invoke(new MethodInvoker(() =>
                        {
                            if (GetComponentById<IAxle>("Y").MaximumSensor.IsActive())
                                Sensor51.Set2();
                            else
                                Sensor51.Set1();
                        }));

                        //传感器
                        Sensor52.Invoke(new MethodInvoker(() =>
                        {
                            if (GetComponentById<IAxle>("Y").MinimumSensor.IsActive())
                                Sensor52.Set2();
                            else
                                Sensor52.Set1();
                        }));

                        if (isCentrifugeConnect)
                        {
                            SensorDoorL.Invoke(new MethodInvoker(() =>
                            {
                                if (leftcentrifuge.GetDoorState() == CentrifugeDoorLocations.Opened)
                                    SensorDoorL.Set2();
                                else
                                    SensorDoorL.Set1();
                            }));

                            SensorDoorR.Invoke(new MethodInvoker(() =>
                            {
                                if (rightcentrifuge.GetDoorState() == CentrifugeDoorLocations.Opened)
                                    SensorDoorR.Set2();
                                else
                                    SensorDoorR.Set1();
                            }));
                        }
                    }
                }
                catch { }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            GetComponentById<IPlcDevice>("Device").ClearError();
        }


        private void btnLeft_Click(object sender, EventArgs e)
        {
            if (leftcentrifuge.GetDoorState() == CentrifugeDoorLocations.Closed)
            {
                leftcentrifuge.StartOpenDoor();
                btnLeft.Text = "关";
            }
            if (leftcentrifuge.GetDoorState() == CentrifugeDoorLocations.Opened)
            {
                leftcentrifuge.StartCloseDoor();
                btnLeft.Text = "开";
            }
        }

        private void btnGoLeft_Click(object sender, EventArgs e)
        {
            //leftcentrifuge.GotoStation(2);
            leftcentrifuge.GotoStation(1);
            while (true)
            {
                if (leftcentrifuge.GetStation() == 1)
                {
                    FastMessageBox.Show("工位校准完成");
                    return;
                }
            }
        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            if (rightcentrifuge.GetDoorState() == CentrifugeDoorLocations.Closed)
            {
                rightcentrifuge.StartOpenDoor();
                btnRight.Text = "关";
            }
            if (rightcentrifuge.GetDoorState() == CentrifugeDoorLocations.Opened)
            {
                rightcentrifuge.StartCloseDoor();
                btnRight.Text = "开";
            }
        }

        private void btnGoRight_Click(object sender, EventArgs e)
        {
            rightcentrifuge.GotoStation(1);
            if (rightcentrifuge.GetStation() == 1)
            {
                FastMessageBox.Show("工位校准完成");
                return;
            }
        }

        private void cbPositionId_SelectedIndexChanged(object sender, EventArgs e)
        {
            var position = (cbPositionId.SelectedItem as T_Position);
            if (position == null) return;
            txtXCoord.Text = position.X.ToString();
            txtYCoord.Text = position.Y.ToString();
            txtZCoord.Text = position.Z.ToString();
            txtSZCoord.Text = position.SZ.ToString();
        }

        private void txtFingerOn_Click(object sender, EventArgs e)
        {
            GetComponentById<ISwitch>("Finger").TurnOff();
        }

        private void btnFingerOff_Click(object sender, EventArgs e)
        {
            GetComponentById<ISwitch>("Finger").TurnOn();
        }

        #region X
        private void btnXWrite_Click(object sender, EventArgs e)
        {
            if (GetComponentById<IAxle>("X").IsZeroCompleted)
            {
                GetComponentById<IAxle>("X").Goto((double)txtXCoord.Value);
                GetComponentById<IAxle>("X").WaitCompleted();
            }
        }

        private void btnXTurntoZero_Click(object sender, EventArgs e)
        {
            GetComponentById<IPlcDevice>("Device").SwitchManualMode();
            GetComponentById<IAxle>("X").StartReturnZero();
            GetComponentById<IAxle>("X").WaitCompleted();
            GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
        }

        private void btnX1_Click(object sender, EventArgs e)
        {
            txtXCoord.Value += -5;
            btnXWrite_Click(null, null);
        }

        private void btnX2_Click(object sender, EventArgs e)
        {
            txtXCoord.Value += -2;
            btnXWrite_Click(null, null);
        }

        private void btnX3_Click(object sender, EventArgs e)
        {
            txtXCoord.Value += -1;
            btnXWrite_Click(null, null);
        }

        private void btnX4_Click(object sender, EventArgs e)
        {
            txtXCoord.Value -= (decimal)0.5;
            btnXWrite_Click(null, null);
        }

        private void btnX5_Click(object sender, EventArgs e)
        {
            txtXCoord.Value -= (decimal)0.2;
            btnXWrite_Click(null, null);
        }

        private void btnX6_Click(object sender, EventArgs e)
        {
            txtXCoord.Value -= (decimal)0.1;
            btnXWrite_Click(null, null);
        }

        private void btnX7_Click(object sender, EventArgs e)
        {
            txtXCoord.Value += (decimal)0.1;
            btnXWrite_Click(null, null);
        }

        private void btnX8_Click(object sender, EventArgs e)
        {
            txtXCoord.Value += (decimal)0.2;
            btnXWrite_Click(null, null);
        }

        private void btnX9_Click(object sender, EventArgs e)
        {
            txtXCoord.Value += (decimal)0.5;
            btnXWrite_Click(null, null);
        }

        private void btnX10_Click(object sender, EventArgs e)
        {
            txtXCoord.Value += 1;
            btnXWrite_Click(null, null);
        }

        private void btnX11_Click(object sender, EventArgs e)
        {
            txtXCoord.Value += 2;
            btnXWrite_Click(null, null);
        }

        private void btnX12_Click(object sender, EventArgs e)
        {
            txtXCoord.Value += 5;
            btnXWrite_Click(null, null);
        }

        private void btnXGo_MouseDown(object sender, MouseEventArgs e)
        {
            GetComponentById<IPlcDevice>("Device").SwitchManualMode();
            GetComponentById<IAxle>("X").StartDecrease();
        }

        private void btnXGo_MouseUp(object sender, MouseEventArgs e)
        {
            GetComponentById<IAxle>("X").StopDecrease();
            GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
        }

        private void btnXBack_MouseDown(object sender, MouseEventArgs e)
        {
            GetComponentById<IPlcDevice>("Device").SwitchManualMode();
            GetComponentById<IAxle>("X").StartIncrease();
        }

        private void btnXBack_MouseUp(object sender, MouseEventArgs e)
        {
            GetComponentById<IAxle>("X").StopIncrease();
            GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
        }


        #endregion


        #region Y
        private void btnYWrite_Click(object sender, EventArgs e)
        {
            if (GetComponentById<IAxle>("Y").IsZeroCompleted)
            {
                GetComponentById<IAxle>("Y").Goto((double)txtYCoord.Value);
                GetComponentById<IAxle>("Y").WaitCompleted();
            }
        }

        private void btnYTurntoZero_Click(object sender, EventArgs e)
        {
            GetComponentById<IPlcDevice>("Device").SwitchManualMode();
            GetComponentById<IAxle>("Y").StartReturnZero();
            GetComponentById<IAxle>("Y").WaitCompleted();
            GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
        }

        private void btnY1_Click(object sender, EventArgs e)
        {
            txtYCoord.Value += -5;
            btnYWrite_Click(null, null);
        }

        private void btnY2_Click(object sender, EventArgs e)
        {
            txtYCoord.Value += -2;
            btnYWrite_Click(null, null);
        }

        private void btnY3_Click(object sender, EventArgs e)
        {
            txtYCoord.Value += -1;
            btnYWrite_Click(null, null);
        }

        private void btnY4_Click(object sender, EventArgs e)
        {
            txtYCoord.Value -= (decimal)0.5;
            btnYWrite_Click(null, null);
        }

        private void btnY5_Click(object sender, EventArgs e)
        {
            txtYCoord.Value -= (decimal)0.2;
            btnYWrite_Click(null, null);
        }

        private void btnY6_Click(object sender, EventArgs e)
        {
            txtYCoord.Value -= (decimal)0.1;
            btnYWrite_Click(null, null);
        }

        private void btnY7_Click(object sender, EventArgs e)
        {
            txtYCoord.Value += (decimal)0.1;
            btnYWrite_Click(null, null);
        }

        private void btnY8_Click(object sender, EventArgs e)
        {
            txtYCoord.Value += (decimal)0.2;
            btnYWrite_Click(null, null);
        }

        private void btnY9_Click(object sender, EventArgs e)
        {
            txtYCoord.Value += (decimal)0.5;
            btnYWrite_Click(null, null);
        }

        private void btnY10_Click(object sender, EventArgs e)
        {
            txtYCoord.Value += 1;
            btnYWrite_Click(null, null);
        }

        private void btnY11_Click(object sender, EventArgs e)
        {
            txtYCoord.Value += 2;
            btnYWrite_Click(null, null);
        }

        private void btnY12_Click(object sender, EventArgs e)
        {
            txtYCoord.Value += 5;
            btnYWrite_Click(null, null);
        }

        private void btnYGo_MouseDown(object sender, MouseEventArgs e)
        {
            GetComponentById<IPlcDevice>("Device").SwitchManualMode();
            GetComponentById<IAxle>("Y").StartDecrease();
        }

        private void btnYGo_MouseUp(object sender, MouseEventArgs e)
        {
            GetComponentById<IAxle>("Y").StopDecrease();
            GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
        }

        private void btnYBack_MouseDown(object sender, MouseEventArgs e)
        {
            GetComponentById<IPlcDevice>("Device").SwitchManualMode();
            GetComponentById<IAxle>("Y").StartIncrease();
        }

        private void btnYBack_MouseUp(object sender, MouseEventArgs e)
        {
            GetComponentById<IAxle>("Y").StopIncrease();
            GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
        }

        #endregion


        #region Z

        private void btnZWrite_Click(object sender, EventArgs e)
        {
            if (isFront)
            {
                if (front.Z.IsZeroCompleted)
                {
                    front.Z.Goto((double)txtZCoord.Value);
                    front.Z.WaitCompleted();
                }
            }
        }

        private void btnZTurntoZero_Click(object sender, EventArgs e)
        {
            if (isFront)
            {
                //if (GetComponentById<IAxle>("X").CurrentCoord == 0 && GetComponentById<IAxle>("Y").CurrentCoord == 0)
                {
                    GetComponentById<IPlcDevice>("Device").SwitchManualMode();
                    front.Z.StartReturnZero();
                    front.Z.WaitCompleted();
                    GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
                }
            }
        }

        private void btnZ1_Click(object sender, EventArgs e)
        {
            txtZCoord.Value += -5;
            btnZWrite_Click(null, null);
        }

        private void btnZ2_Click(object sender, EventArgs e)
        {
            txtZCoord.Value += -2;
            btnZWrite_Click(null, null);
        }

        private void btnZ3_Click(object sender, EventArgs e)
        {
            txtZCoord.Value += -1;
            btnZWrite_Click(null, null);
        }

        private void btnZ4_Click(object sender, EventArgs e)
        {
            txtZCoord.Value -= (decimal)0.1;
            btnZWrite_Click(null, null);
        }

        private void btnZ5_Click(object sender, EventArgs e)
        {
            txtZCoord.Value -= (decimal)0.2;
            btnZWrite_Click(null, null);
        }

        private void btnZ6_Click(object sender, EventArgs e)
        {
            txtZCoord.Value -= (decimal)0.5;
            btnZWrite_Click(null, null);
        }

        private void btnZ7_Click(object sender, EventArgs e)
        {
            txtZCoord.Value += (decimal)0.1;
            btnZWrite_Click(null, null);
        }

        private void btnZ8_Click(object sender, EventArgs e)
        {
            txtZCoord.Value += (decimal)0.2;
            btnZWrite_Click(null, null);
        }

        private void btnZ9_Click(object sender, EventArgs e)
        {
            txtZCoord.Value += (decimal)0.5;
            btnZWrite_Click(null, null);
        }

        private void btnZ10_Click(object sender, EventArgs e)
        {
            txtZCoord.Value += 1;
            btnZWrite_Click(null, null);
        }

        private void btnZ11_Click(object sender, EventArgs e)
        {
            txtZCoord.Value += 2;
            btnZWrite_Click(null, null);
        }

        private void btnZ12_Click(object sender, EventArgs e)
        {
            txtZCoord.Value += 5;
            btnZWrite_Click(null, null);
        }


        private void btnZGo_MouseDown(object sender, MouseEventArgs e)
        {
            if (isFront)
            {
                GetComponentById<IPlcDevice>("Device").SwitchManualMode();
                front.Z.StartDecrease();
            }
        }

        private void btnZGo_MouseUp(object sender, MouseEventArgs e)
        {
            if (isFront)
            {
                front.Z.StopDecrease();
                GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
            }
        }

        private void btnZBack_MouseDown(object sender, MouseEventArgs e)
        {
            if (isFront)
            {
                GetComponentById<IPlcDevice>("Device").SwitchManualMode();
                front.Z.StartIncrease();
            }
        }

        private void btnZBack_MouseUp(object sender, MouseEventArgs e)
        {
            if (isFront)
            {
                front.Z.StopIncrease();
                GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
            }
        }
        #endregion

        #region SZ
        private void btnSZWrite_Click(object sender, EventArgs e)
        {
            if (!ck5.Checked && txtSZCoord.Text == "5")
            {
                return;
            }
            double zoord = 0;
            double.TryParse(txtSZCoord.Text, out zoord);

            GetComponentById<IAxle>("SZ").Goto(zoord);
            GetComponentById<IAxle>("SZ").WaitCompleted();
        }
        private void btnSZTurntoZero_Click(object sender, EventArgs e)
        {
            GetComponentById<IPlcDevice>("Device").SwitchManualMode();
            GetComponentById<IAxle>("SZ").StartReturnZero();
          //  GetComponentById<IAxle>("SZ").WaitCompleted();
            GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
        }



        #endregion

        private void btnXSave_Click(object sender, EventArgs e)
        {
            SaveRange();
        }

        private void btnYSave_Click(object sender, EventArgs e)
        {
            SaveRange();
        }

        private void btnZSave_Click(object sender, EventArgs e)
        {
            SaveRange();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            decimal XCoord = 0;
            decimal YCoord = 0;
            decimal ZCoord = 0;
            decimal.TryParse(txtXCoord.Text, out XCoord);
            decimal.TryParse(txtYCoord.Text, out YCoord);
            decimal.TryParse(txtZCoord.Text, out ZCoord);

            PropertyHelper json = new PropertyHelper();
            json.Addproperty(CompareType.Equal, "Id", cbPositionId.Text);
            string jsonWhere = JsonConvert.SerializeObject(json.propertyList);
            string url = string.Format("Position/Find?jsonWhere={0}", jsonWhere);
            var position = WebAPIHelper.Get<T_Position>(url);
            if (position == null)
            {
                position = new T_Position()
                {
                    Id = cbPositionId.Text,
                    PositionType = (long?)cbType.SelectedIndex,
                    X = XCoord,
                    Y = YCoord,
                    Z = ZCoord,
                    SZ = txtSZCoord.SelectedIndex
                };
                WebAPIHelper.Post<T_Position>("Position/Add", position);
            }
            else
            {
                position.PositionType = (long?)cbType.SelectedIndex;
                position.X = XCoord;
                position.Y = YCoord;
                position.Z = ZCoord;
                position.SZ = txtSZCoord.SelectedIndex;
                WebAPIHelper.Post<T_Position>("Position/Modify", position);
            }
        }

        private void SaveRange()
        {
            if (range == null) range = new XYZRange();
            range.XMinimumLimit = txtXMin.Value;
            range.XMaximumLimit = txtXMax.Value;
            range.YMinimumLimit = txtYMin.Value;
            range.YMaximumLimit = txtYMax.Value;
            range.ZMinimumLimit = txtZMin.Value;
            range.ZMaximumLimit = txtZMax.Value;


            string fp = Application.StartupPath + (isFront ? "\\front" : "\\back") + ".json";
            if (!File.Exists(fp))  // 判断是否已有相同文件 
            {
                FileStream fs1 = new FileStream(fp, FileMode.Create, FileAccess.ReadWrite);
                fs1.Close();
            }
            File.WriteAllText(fp, JsonConvert.SerializeObject(range));

        }

        private void txtXCurcoord_EditValueChanged(object sender, EventArgs e)
        {
            decimal coord;
            decimal.TryParse(txtXCurcoord.Text, out coord);
            txtXCoord.Value = coord;
        }

        private void txtYCurcoord_EditValueChanged(object sender, EventArgs e)
        {
            decimal coord;
            decimal.TryParse(txtYCurcoord.Text, out coord);
            txtYCoord.Value = coord;
        }

        private void txtZCurcoord_EditValueChanged(object sender, EventArgs e)
        {
            decimal coord;
            decimal.TryParse(txtZCurcoord.Text, out coord);
            txtZCoord.Value = coord;
        }

        private void txtSZCurcoord_EditValueChanged(object sender, EventArgs e)
        {
            decimal coord;
            decimal.TryParse(txtSZCurcoord.Text, out coord);
            txtSZCoord.EditValue = coord;
        }

        private void btnAuto_Click(object sender, EventArgs e)
        {

        }

        private void Position_FormClosing(object sender, FormClosingEventArgs e)
        {
            //            if (plc.IsOpened)
            //                plc.Close();
        }

        private void btnXGo_Click(object sender, EventArgs e)
        {

        }

        private void btnAuto_Click_1(object sender, EventArgs e)
        {
            if (isFront)
                GetComponentById<IPlcDevice>("Device").SwitchAutoMode();
            else
                back.Device.SwitchAutoMode();
        }

        private void btnM_Click(object sender, EventArgs e)
        {
            if (isFront)
                GetComponentById<IPlcDevice>("Device").SwitchManualMode();
            else
                back.Device.SwitchManualMode();
        }

        private T GetComponentById<T>(string name)
        {
            if (isFront) return (T)front.GetType().GetProperty(name).GetValue(front);
            if (isBack2) return (T)back2.GetType().GetProperty(name).GetValue(back2);
            return (T)back.GetType().GetProperty(name).GetValue(back);
        }
    }

    public class XYZRange
    {
        public decimal XMinimumLimit { get; set; }
        public decimal XMaximumLimit { get; set; }
        public decimal YMinimumLimit { get; set; }
        public decimal YMaximumLimit { get; set; }
        public decimal ZMinimumLimit { get; set; }
        public decimal ZMaximumLimit { get; set; }

    }
}
